<template>
  <div style="display:inline-block">
    <!--
      :value-key="renderKey.renderValue"
     -->
    <el-select
      :value="selectValue"
      :placeholder="placeholder"
      :disabled="disabled"
      :loading="isLoading"
      style="width: 100%;"
      :value-key="renderKey.renderKey"
      filterable
      :clearable="clearable"
      @focus="sendUrl"
      @change="selChange"
    >
      <template #prefix>
        <slot name="prefix" />
      </template>
      <!-- 显示什么绑定什么,等提交再转换 -->
      <el-option
        v-for="(item1, index) in item.opintion"
        :key="index"
        :label="item1[renderKey.renderValue]"
        :value="item1[renderKey.renderKey]"
      />
    </el-select>
  </div>
</template>

<script type="text/ecmascript-6">
// import { getCommonDataByUrl } from '@/api/commonRequest';
import { getCommonData } from '@/api/reportCenter';
import { getUnit } from '@/api/login/index';
import _ from 'lodash';
import {
  filterRequestData,
  dealRequestData,
  setFatherNode
} from '../common';
export default {
  props: {
    placeholder: {
      type: String,
      default: ''
    },

    item: {
      type: Object,
      default: () => ({})
    },

    disabled: {
      type: Boolean,
      default: false
    },

    selectValue: {
      type: [String, Number],
      default: () => {
        return '';
      }
    },
    params: {
      type: Object,
      default: () => ({})
    },
    clearable: {
      type: Boolean,
      default: true
    }
  },

  // inject: ['formData'],
  inject: {
    formData: {
      from: 'formData',
      default: ''
    }
  },

  data() {
    return {
      // sel: '',
      opintion: [],
      renderKey: {},
      isLoading: false
    };
  },

  computed: {
    getFormData() {
      if (this.formData) {
        return this.formData();
      } else {
        return undefined;
      }
    }
  },

  created() {
    this.initData();
  },

  methods: {
    initData() {
      const { item } = this;
      // this.sel = item.myValue;
      this.opintion = item.opintion;
      if (JSON.stringify(item.selectViewOptions) !== '{}') {
        this.renderKey = item.selectViewOptions;
      } else {
        this.renderKey = {
          renderKey: 'lable',
          renderMapKey: 'value',
          renderValue: 'lable'
        };
      }
      // 所属部门直接掉接口判断
      if (item.componentType === 'enterpriseIn') {
        item.selectViewOptions = this.renderKey = {
          renderKey: 'name',
          renderMapKey: 'id',
          renderValue: 'name'
        };
        const obj = {
          userId: localStorage.getItem('xcUserId'),
          resultAsTree: false,
          isHideParent: true
        };
        getUnit(obj).then(res => {
          const { success, data } = res;
          if (success && data) {
            data.map(v => {
              v.id = v.id + '';
            });
            if (JSON.stringify(item.selectViewOptions) === '{}') {
              item.selectViewOptions = this.renderKey = {
                renderKey: 'name',
                renderMapKey: 'id',
                renderValue: 'name'
              };
            }
            item.opintion = data;
            if (data.length === 1) {
              this.$emit('change', data[0]);
            }
          } else {
            item.opintion = [];
          }
        });
      }
    },

    // 请求后台
    sendUrl() {
      const { item, opintion } = this;
      const {
        focusUrlParams
      } = item;
      if (item.opintion && item.opintion.length && !focusUrlParams.other) {
        this.opintion = item.opintion;
        return;
        // 全部部门
      } else if (item.componentType === 'enterpriseList') {
        const obj = {
          userId: localStorage.getItem('xcUserId'),
          resultAsTree: false,
          showBindOnly: false,
          isHideParent: true
        };
        getUnit(obj).then(res => {
          const { success, data } = res;
          if (success && data) {
            data.map(v => {
              v.id = v.id + '';
            });
            item.selectViewOptions = this.renderKey = {
              renderKey: 'name',
              renderMapKey: 'id',
              renderValue: 'name'
            };

            item.opintion = data;
          } else {
            item.opintion = [];
          }
        });
        return;
      }
      if (!opintion.length || focusUrlParams.other) {
        this.isLoading = true;
        if (!focusUrlParams || !item.focusUrl || JSON.stringify(focusUrlParams) === '{}') return this.$message.error('请求参数未配置');

        let endREquestPayload = _.cloneDeep(focusUrlParams);
        if (this.getFormData) {
          if (focusUrlParams.other) {
            endREquestPayload = filterRequestData(focusUrlParams, this.getFormData, this.item);
            if (!endREquestPayload) {
              return;
            }
          }
        }
        if (focusUrlParams.other && JSON.stringify(this.params) !== '{}') {
          const urlParams = _.cloneDeep(focusUrlParams);
          endREquestPayload = dealRequestData(urlParams, this.params);
        }
        // if (!item.focusUrl.includes('http')) {
        // this.$message.warning('请在后台接口配置内输入完整地址(http://10.10.10.61/....)');
        //   return;
        // }
        endREquestPayload && getCommonData(endREquestPayload, item.focusUrl).then(({ data: res }) => {
          this.isLoading = false;
          if (res.success && res.data) {
            setFatherNode(res.data);
            this.$emit('changeItemOption', {
              option: res.data,
              item: this.item
            });
          } else {
            this.$emit('changeItemOption', {
              option: [],
              item: this.item
            });
          }
        });
      }
    },

    selChange(value) {
      let item = this.item.opintion.find(v => v[this.renderKey.renderKey] === value);
      // 显示什么绑定什么,等提交再转换
      // let item = this.item.opintion.find(v => v[this.renderKey.renderValue] === value);
      // 清空
      if (!item) {
        item = {};
        const keys = Object.keys(this.item.opintion[0]);
        keys.forEach(v => {
          item[v] = '';
        });
      }
      this.$emit('change', item);
    }

    // 赋值(从外面调用)
    // setSelectItem({ value = '', opintion = [] }) {
    //   // this.sel = value;
    //   if (opintion.length) {
    //     this.opintion = opintion;
    //   }
    // }

  }
};
</script>

<style lang="scss" scoped>
</style>
